import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import type { MessageItem, ChatResponse, ChatLog } from '@/types'
import { chatApi } from '@/api'
import { ElMessage } from 'element-plus'

export const useChatStore = defineStore('chat', () => {
  // 状态
  const sessionId = ref<string>('')
  const messages = ref<MessageItem[]>([])
  const chatHistory = ref<ChatLog[]>([])
  const isLoading = ref(false)
  const isConnected = ref(false)

  // 计算属性
  const messageCount = computed(() => messages.value.length)
  const lastMessage = computed(() => messages.value[messages.value.length - 1])

  // 初始化会话
  function initializeSession() {
    if (!sessionId.value) {
      sessionId.value = generateSessionId()
    }
    
    // 添加欢迎消息
    if (messages.value.length === 0) {
      addSystemMessage('欢迎使用AI数据库管理助手！您可以用自然语言与数据库进行交互。\n\n示例问题：\n• 查询所有用户\n• 查找年龄大于25岁的用户\n• 添加一个新用户\n• 统计活跃用户数量')
    }
    
    // 检查连接状态
    checkConnection()
  }

  // 生成会话ID
  function generateSessionId(): string {
    return `session_${Date.now()}_${Math.random().toString(36).substring(2, 15)}`
  }

  // 检查连接状态
  async function checkConnection() {
    try {
      await chatApi.healthCheck()
      isConnected.value = true
    } catch (error) {
      isConnected.value = false
      console.error('连接检查失败:', error)
    }
  }

  // 发送消息
  async function sendMessage(content: string, includeDetails: boolean = false) {
    if (!content.trim()) {
      ElMessage.warning('请输入问题')
      return
    }

    // 添加用户消息
    const userMessage: MessageItem = {
      id: generateMessageId(),
      type: 'user',
      content: content.trim(),
      timestamp: Date.now()
    }
    messages.value.push(userMessage)

    // 添加加载中的助手消息
    const assistantMessage: MessageItem = {
      id: generateMessageId(),
      type: 'assistant',
      content: '',
      timestamp: Date.now(),
      loading: true
    }
    messages.value.push(assistantMessage)

    isLoading.value = true

    try {
      // 调用API
      const response: ChatResponse = await chatApi.sendMessage({
        sessionId: sessionId.value,
        question: content.trim(),
        includeDetails
      })

      // 更新助手消息
      const assistantIndex = messages.value.findIndex(msg => msg.id === assistantMessage.id)
      if (assistantIndex !== -1) {
        messages.value[assistantIndex] = {
          ...assistantMessage,
          content: response.message,
          loading: false,
          error: !response.success,
          data: {
            databaseResult: response.databaseResult,
            intentResult: includeDetails ? response.intentResult : undefined,
            executionTime: response.totalExecutionTime
          }
        }
      }

      if (!response.success) {
        ElMessage.error(response.errorMessage || '处理请求失败')
      }

    } catch (error) {
      // 更新助手消息为错误状态
      const assistantIndex = messages.value.findIndex(msg => msg.id === assistantMessage.id)
      if (assistantIndex !== -1) {
        messages.value[assistantIndex] = {
          ...assistantMessage,
          content: `抱歉，处理您的请求时遇到了错误：${error instanceof Error ? error.message : '未知错误'}`,
          loading: false,
          error: true
        }
      }

      ElMessage.error('发送消息失败，请检查网络连接')
      console.error('发送消息失败:', error)
    } finally {
      isLoading.value = false
    }
  }

  // 添加系统消息
  function addSystemMessage(content: string) {
    const systemMessage: MessageItem = {
      id: generateMessageId(),
      type: 'system',
      content,
      timestamp: Date.now()
    }
    messages.value.push(systemMessage)
  }

  // 生成消息ID
  function generateMessageId(): string {
    return `msg_${Date.now()}_${Math.random().toString(36).substring(2, 15)}`
  }

  // 清除消息
  function clearMessages() {
    messages.value = []
    addSystemMessage('聊天记录已清空')
  }

  // 加载聊天历史
  async function loadChatHistory() {
    try {
      const history = await chatApi.getChatHistory(sessionId.value)
      chatHistory.value = history
    } catch (error) {
      console.error('加载聊天历史失败:', error)
      ElMessage.error('加载聊天历史失败')
    }
  }

  // 清除聊天历史
  async function clearChatHistory() {
    try {
      await chatApi.clearChatHistory(sessionId.value)
      chatHistory.value = []
      clearMessages()
      ElMessage.success('聊天历史已清除')
    } catch (error) {
      console.error('清除聊天历史失败:', error)
      ElMessage.error('清除聊天历史失败')
    }
  }

  // 重新开始会话
  function startNewSession() {
    sessionId.value = generateSessionId()
    clearMessages()
    addSystemMessage('新会话已开始')
  }

  return {
    // 状态
    sessionId,
    messages,
    chatHistory,
    isLoading,
    isConnected,
    
    // 计算属性
    messageCount,
    lastMessage,
    
    // 方法
    initializeSession,
    sendMessage,
    addSystemMessage,
    clearMessages,
    loadChatHistory,
    clearChatHistory,
    startNewSession,
    checkConnection
  }
})